<#include "${ftl_skin}/common/header.ftl">


<style type="text/css">
    .ztree li span.button.add {margin-left:2px; margin-right: -1px; background-position:-144px 0; vertical-align:top; *vertical-align:middle}
</style>


</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="ibox float-e-margins">
        <div class="ibox-title">地区管理</div>
        <div class="ibox-content">


            <div class="row">
                <div class="col-xs-3">
                    <div id="treeDiv" class='ztree'></div>
                </div>
                <div class="col-xs-9" id="rightDiv">
                    <!--工具条按钮-->
                    <div class="btn-group">

                        <button type="button" class="btn btn-info" onClick="javascript:addTopNode();return false;">添加顶级结点</button>

                        <button type="button" class="btn btn-info" onClick="javascript:addChildNode();return false;">添加子结点</button>

                        <button type="button" class="btn btn-info dragBtn" onClick="javascript:setDrag(true);return false;">打开拖动(可跨父结点拖动)</button>

                        <button type="button" class="btn btn-warning dragBtn" onClick="javascript:setDrag(false);return false;" style="display:none;">关闭拖动(可跨父结点拖动)</button>

                        <button type="button" class="btn btn-info" onClick="javascript:delNode();return false;">删除</button>


                    </div>
                    <!--工具条按钮 END-->

                    <br />

                    <iframe src="${path.viewPath}/index/blank.do" frameborder="0" name="treesetiframe" id="treesetiframe" scrolling="auto"> </iframe>
                </div>
            </div>


        </div><!-- end ibox-content -->
    </div><!-- end ibox -->
</div><!-- end wrap -->



<#include "${ftl_skin}/common/js.ftl">




<script type="text/javascript" src="${path.commonPath }tools/yxTree/yx.yxTree.js"></script>


<link rel="stylesheet" href="${path.commonPath }tools/zTree_v3/css/zTreeStyle/zTreeStyle.css" type="text/css">
<script type="text/javascript" src="${path.commonPath }tools/zTree_v3/js/jquery.ztree.core-3.5.js"></script>
<script type="text/javascript" src="${path.commonPath }tools/zTree_v3/js/jquery.ztree.exedit-3.5.js"></script>

<script type="text/javascript">
    var tree = new yxTree('tree');

    $(function(){

        $.ajax({
            url: "${path.servicePath}/menu/treelistauth.do",
            async: false,
            type: 'POST',
            data: {parent_tree_code:'${parentSeqCode}'},
            complete:function(XMLHttpRequest, textStatus){
//                 alert(XMLHttpRequest.responseText);
            },
            success: function(data){
                if(data.state == 0){
                    var msg = data.result;

                    for(var i in msg){
//                         alert(msg[i].PARENT_TREE_CODE + '_' + msg[i].TREE_CODE);
                        tree.nodes[msg[i].parent_tree_code + '_' + msg[i].tree_code] = 'text:' + msg[i].node_name + ';url:' + msg[i].url + ';';
                    }
//                    tree.toString('treeDiv');

                    //输出 json 格式
                    var treeNodes = tree.toArr();
                    var json = [];

                    treeToJson(json, treeNodes[0].childNodes);

//                    alert(JSON.stringify(json));
                    initZTree(json);
                }
            }
        });

        winSizeEvent(loadWinSize); // 窗口自动调整
    });


    // 控制页面布局 ( 根据浏览器可视面积动态改变 宽高度 )
    function loadWinSize(){

        // 控制页面布局 ( 根据浏览器可视面积动态改变 宽高度 )
        $('#treesetiframe').height($(window).height() - 180);
        $('#treesetiframe').width($('#rightDiv').width());


    }



    //把数组转换成 json
    function treeToJson(json, treeNodeArr){
        for(var i = 0; i < treeNodeArr.length; i++){
            var tmpJson = {};
            tmpJson.id = treeNodeArr[i].sourceId;
            tmpJson.name = treeNodeArr[i].text;
            // tmpJson.url = treeNodeArr[i].url;
            tmpJson.target = 'treesetiframe';
            tmpJson.open = true;
            if(treeNodeArr[i].hasChild){
                tmpJson.isParent = true;
                tmpJson.children = [];
                treeToJson(tmpJson.children, treeNodeArr[i].childNodes);
            }
            json.push(tmpJson);
        }
    }

    function initZTree(json){

        var setting = {
            view: {
                selectedMulti: false
            },
            edit: {
                drag: {
                    autoExpandTrigger: true,
                    prev: dropPrev,
                    inner: dropInner,
                    next: dropNext
                },
                enable: false,  //手工打开编辑模式
                editNameSelectAll: false,
                showRemoveBtn: false,
                showRenameBtn: false
            },
            data: {
                simpleData: {
                    enable:true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: ""
                }
            },
            callback: {
                beforeClick: function(treeId, treeNode) {
                    // alert(treeNode.name + ":" + treeNode.id);
                    $('#' + treeId).attr('nodeName', treeNode.name).attr('nodeId', treeNode.id);

                    $('#treesetiframe').attr('src', '${path.viewPath}/menu/tnodeedit.do?TREE_CODE=' + treeNode.id);
                },

                beforeDrag: beforeDrag,
                onDrop: onDrop

            }
        };

        var zTree = $.fn.zTree.init($("#treeDiv"), setting, json);
    }


    //========================拖动方法(只允许本级别拖动)======================

    function dropPrev(treeId, nodes, targetNode) {  //只允许同级别移动（相同的父结点）
//        var pNode = targetNode.getParentNode();
//        if (pNode && pNode.dropInner === false) {
//            return false;
//        } else {
//            for (var i=0,l=curDragNodes.length; i<l; i++) {
//                var curPNode = curDragNodes[i].getParentNode();
//                if (curPNode && curPNode !== targetNode.getParentNode()) {
//                    return false;
//                }
//            }
//        }
        return true;
    }

    function dropInner(treeId, nodes, targetNode) { //不能拖动成为子结点
        return true;
    }
    function dropNext(treeId, nodes, targetNode) {  //只允许同级别移动（相同的父结点）
//        var pNode = targetNode.getParentNode();
//        if (pNode && pNode.dropInner === false) {
//            return false;
//        } else {
//            for (var i=0,l=curDragNodes.length; i<l; i++) {
//                var curPNode = curDragNodes[i].getParentNode();
//                if (curPNode && curPNode !== targetNode.getParentNode()) {
//                    return false;
//                }
//            }
//        }
        return true;
    }

    var log, className = "dark", curDragNodes, autoExpandNode;
    function beforeDrag(treeId, treeNodes) {  //取到当前正在拖动中的节点，放到 curDragNodes 里面
        className = (className === "dark" ? "":"dark");

        for (var i=0,l=treeNodes.length; i<l; i++) {
            if (treeNodes[i].drag === false) {
                curDragNodes = null;
                return false;
            } else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
                curDragNodes = null;
                return false;
            }
        }
        curDragNodes = treeNodes;
        return true;
    }
    function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) { //当节点已经放下后，才进行排序操作，要不排序不生效

        var zTree = $.fn.zTree.getZTreeObj(treeId);

        var dragNode = treeNodes[0];  //拖动中的结点，一般只有一个结点；

        /*
        var HOrder = '';
        var pNode = targetNode.getParentNode();
        for(var i = 0; i < pNode.children.length; i++){
          HOrder += pNode.children[i].id + "," + zTree.getNodeIndex(pNode.children[i]) + ";";
        }
        HOrder = getSubString(HOrder, HOrder.length - 1);
        */
        // alert(targetNode.id + ":" +  targetNode.name + ":" + zTree.getNodeIndex(targetNode));
        //开始保存
        var dragState = false;

        var parentSeqCodeVal = '-1';
        if(dragNode.level != 0){
            parentSeqCodeVal = dragNode.getParentNode().id;
        }
        $.ajax({
            url: '${path.servicePath}/menu/tnodemove2.do',
            async: false,
            type: 'POST',
            data: {
                treeCode:dragNode.id,
                nodeOrder:zTree.getNodeIndex(dragNode) + 1,
                parentTreeCode:parentSeqCodeVal,
                nodeDeep: dragNode.level + 1
            },
            complete:function(XMLHttpRequest, textStatus){
                // alert(XMLHttpRequest.responseText);
            },
            success: function(msg){
                if(msg.state == 0){
                    dragState = true;
                }
            }
        });

        return dragState;
    }



    //===========================按钮操作================================//

    //添加顶级结点
    function addTopNode(){
        $('#treesetiframe').attr('src', '${path.viewPath}/menu/tnodeadd.do?node_deep=1&parent_tree_code=-1');
    }

    //添加子结点
    function addChildNode(){
        if(isSet($('#treeDiv').attr('nodeId'))){
            var curtNodeDeep = $('#treeDiv').attr('nodeId').length / 3;
            $('#treesetiframe').attr('src', '${path.viewPath}/menu/tnodeadd.do?node_deep=' + (curtNodeDeep+1) + '&parent_tree_code=' + $('#treeDiv').attr('nodeId'));
        }else{
            alert('请先选择结点！');
        }
    }

    function addNodeCB(parentNodeId, addNode){
        var treeObj = $.fn.zTree.getZTreeObj("treeDiv");

        // var zTree = $.fn.zTree.getZTreeObj("treeDiv");
        // zTree.addNodes(treeNode, {id:msg.moduleSeq, pId:treeNode.id, name:"新结点" + (newCount++)});

        if(parentNodeId == null){
            newNode = treeObj.addNodes(null, addNode);
        }else{
            var parentNode = treeObj.getNodeByParam("id", parentNodeId);
            newNode = treeObj.addNodes(parentNode, addNode);
        }
    }

    function editNodeCB(nodeId, nodeName){
        var treeObj = $.fn.zTree.getZTreeObj("treeDiv");

        var node = treeObj.getNodeByParam("id", nodeId);
        node.name = nodeName;
        treeObj.updateNode(node);
    }

    //设置拖动
    function setDrag(flag){
        var treeObj = $.fn.zTree.getZTreeObj("treeDiv");
        treeObj.setEditable(flag);

        $('.dragBtn').toggle();
    }

    //删除结点
    function delNode(){
        if(isSet($('#treeDiv').attr('nodeId'))){

            HFConfirm("确定删除结点[ " + $('#treeDiv').attr('nodeName') + " ]? 将会级联删除其所有子结点!", "", "warning", function(isConfirm){
                if(isConfirm){

                    var treeObj = $.fn.zTree.getZTreeObj("treeDiv");
                    var node = treeObj.getNodeByParam("id", $('#treeDiv').attr('nodeId'));


                    HFAjax("${path.servicePath }menu/tnodedel.do", {
                        treeCode : node.id,
                        parentTreeCode : node.pId
                    }, function(result){
                        HFToastrTipResult(result);
                        treeObj.removeNode(node, false);  //删除节点，并且不触发回调函数
                        $('#treesetiframe').attr('src', "${path.viewPath}/index/blank.do");
                    });
                }
            });


        }else{
            HFAlert('请先选择结点！');
        }

    }
</script>

<#include "${ftl_skin}/common/footer.ftl">
